<template>
  <el-dialog
    :model-value="visible"
    title="权限管理"
    width="700px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div v-if="user" class="permission-management">
      <!-- 用户信息 -->
      <el-card class="user-info-card" shadow="never">
        <div class="user-info">
          <el-avatar :size="60" :src="user.avatar">
            {{ user.name?.charAt(0) }}
          </el-avatar>
          <div class="user-details">
            <div class="user-name">{{ user.name }}</div>
            <div class="user-role">{{ translateRole(user.role) }}</div>
          </div>
        </div>
      </el-card>

      <!-- 权限设置 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权限模板" prop="template">
          <el-select
            v-model="form.template"
            placeholder="选择权限模板"
            style="width: 100%"
            @change="handleTemplateChange"
          >
            <el-option label="自定义" value="custom" />
            <el-option label="管理员" value="admin" />
            <el-option label="经理" value="manager" />
            <el-option label="客服" value="agent" />
            <el-option label="客户" value="customer" />
          </el-select>
        </el-form-item>

        <!-- 工单权限 -->
        <el-form-item label="工单权限">
          <div class="permission-section">
            <div class="permission-group">
              <h4>基础权限</h4>
              <el-checkbox-group v-model="form.permissions">
                <el-checkbox value="ticket:read">查看工单</el-checkbox>
                <el-checkbox value="ticket:create">创建工单</el-checkbox>
              </el-checkbox-group>
            </div>
            
            <div class="permission-group">
              <h4>管理权限</h4>
              <el-checkbox-group v-model="form.permissions">
                <el-checkbox value="ticket:update">更新工单</el-checkbox>
                <el-checkbox value="ticket:delete">删除工单</el-checkbox>
                <el-checkbox value="ticket:assign">指派工单</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>

        <!-- 用户管理权限 -->
        <el-form-item label="用户管理">
          <div class="permission-section">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="user:manage">用户管理</el-checkbox>
              <el-checkbox value="user:create">创建用户</el-checkbox>
              <el-checkbox value="user:update">更新用户</el-checkbox>
              <el-checkbox value="user:delete">删除用户</el-checkbox>
              <el-checkbox value="user:permission">权限管理</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <!-- 系统权限 -->
        <el-form-item label="系统权限">
          <div class="permission-section">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="system:config">系统配置</el-checkbox>
              <el-checkbox value="system:backup">数据备份</el-checkbox>
              <el-checkbox value="system:log">系统日志</el-checkbox>
              <el-checkbox value="system:monitor">系统监控</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <!-- 报表权限 -->
        <el-form-item label="报表权限">
          <div class="permission-section">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="report:view">查看报表</el-checkbox>
              <el-checkbox value="report:export">导出报表</el-checkbox>
              <el-checkbox value="report:create">创建报表</el-checkbox>
              <el-checkbox value="report:schedule">定时报表</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <!-- 通知权限 -->
        <el-form-item label="通知权限">
          <div class="permission-section">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="notification:send">发送通知</el-checkbox>
              <el-checkbox value="notification:template">通知模板</el-checkbox>
              <el-checkbox value="notification:schedule">定时通知</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <!-- 权限说明 -->
        <el-form-item label="权限说明">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限变更说明（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 生效时间 -->
        <el-form-item label="生效时间" prop="effectiveTime">
          <el-date-picker
            v-model="form.effectiveTime"
            type="datetime"
            placeholder="选择生效时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 通知用户 -->
        <el-form-item label="通知用户" prop="notifyUser">
          <el-switch
            v-model="form.notifyUser"
            active-text="通知"
            inactive-text="不通知"
          />
          <span class="form-tip">权限变更后将通过邮件和系统通知用户</span>
        </el-form-item>
      </el-form>

      <!-- 权限预览 -->
      <el-card class="preview-card" shadow="never">
        <template #header>
          <h4>权限预览</h4>
        </template>
        <div class="permission-preview">
          <div class="preview-section">
            <h5>工单权限</h5>
            <div class="permission-tags">
              <el-tag
                v-for="permission in getTicketPermissions()"
                :key="permission"
                size="small"
                type="success"
              >
                {{ translatePermission(permission) }}
              </el-tag>
            </div>
          </div>
          
          <div class="preview-section">
            <h5>用户管理权限</h5>
            <div class="permission-tags">
              <el-tag
                v-for="permission in getUserPermissions()"
                :key="permission"
                size="small"
                type="primary"
              >
                {{ translatePermission(permission) }}
              </el-tag>
            </div>
          </div>
          
          <div class="preview-section">
            <h5>系统权限</h5>
            <div class="permission-tags">
              <el-tag
                v-for="permission in getSystemPermissions()"
                :key="permission"
                size="small"
                type="warning"
              >
                {{ translatePermission(permission) }}
              </el-tag>
            </div>
          </div>
          
          <div class="preview-section">
            <h5>报表权限</h5>
            <div class="permission-tags">
              <el-tag
                v-for="permission in getReportPermissions()"
                :key="permission"
                size="small"
                type="info"
              >
                {{ translatePermission(permission) }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存权限' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'

export default {
  name: 'PermissionDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const userStore = useUserStore()
    const formRef = ref()
    const submitting = ref(false)

    // 表单数据
    const form = reactive({
      template: 'custom',
      permissions: [],
      description: '',
      effectiveTime: '',
      notifyUser: true
    })

    // 表单验证规则
    const rules = {
      effectiveTime: [
        { required: true, message: '请选择生效时间', trigger: 'change' }
      ]
    }

    // 权限模板
    const permissionTemplates = {
      admin: [
        'ticket:read', 'ticket:create', 'ticket:update', 'ticket:delete', 'ticket:assign',
        'user:manage', 'user:create', 'user:update', 'user:delete', 'user:permission',
        'system:config', 'system:backup', 'system:log', 'system:monitor',
        'report:view', 'report:export', 'report:create', 'report:schedule',
        'notification:send', 'notification:template', 'notification:schedule'
      ],
      manager: [
        'ticket:read', 'ticket:create', 'ticket:update', 'ticket:assign',
        'user:manage', 'user:create', 'user:update',
        'report:view', 'report:export', 'report:create',
        'notification:send', 'notification:template'
      ],
      agent: [
        'ticket:read', 'ticket:create', 'ticket:update', 'ticket:assign'
      ],
      customer: [
        'ticket:read', 'ticket:create'
      ]
    }

    // 监听user变化，初始化表单
    watch(() => props.user, (newUser) => {
      if (newUser) {
        Object.assign(form, {
          template: 'custom',
          permissions: [...(newUser.permissions || [])],
          description: '',
          effectiveTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
          notifyUser: true
        })
      }
    }, { immediate: true })

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (visible) => {
      if (visible && props.user) {
        form.permissions = [...(props.user.permissions || [])]
        form.template = 'custom'
        form.description = ''
        form.effectiveTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
        form.notifyUser = true
        formRef.value?.clearValidate()
      }
    })

    // 处理模板变化
    const handleTemplateChange = (template) => {
      if (template !== 'custom') {
        form.permissions = [...(permissionTemplates[template] || [])]
      }
    }

    // 获取工单权限
    const getTicketPermissions = () => {
      return form.permissions.filter(p => p.startsWith('ticket:'))
    }

    // 获取用户管理权限
    const getUserPermissions = () => {
      return form.permissions.filter(p => p.startsWith('user:'))
    }

    // 获取系统权限
    const getSystemPermissions = () => {
      return form.permissions.filter(p => p.startsWith('system:'))
    }

    // 获取报表权限
    const getReportPermissions = () => {
      return form.permissions.filter(p => p.startsWith('report:'))
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 准备提交数据
        const submitData = {
          permissions: form.permissions,
          description: form.description,
          effectiveTime: form.effectiveTime,
          notifyUser: form.notifyUser
        }

        await userStore.updateUserPermissions(props.user.id, submitData)
        
        ElMessage.success('权限更新成功！')
        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    // 工具方法
    const translateRole = (role) => {
      const roleMap = {
        admin: '管理员',
        manager: '经理',
        agent: '客服',
        customer: '客户'
      }
      return roleMap[role] || role
    }

    const translatePermission = (permission) => {
      const permissionMap = {
        'ticket:read': '查看工单',
        'ticket:create': '创建工单',
        'ticket:update': '更新工单',
        'ticket:delete': '删除工单',
        'ticket:assign': '指派工单',
        'user:manage': '用户管理',
        'user:create': '创建用户',
        'user:update': '更新用户',
        'user:delete': '删除用户',
        'user:permission': '权限管理',
        'system:config': '系统配置',
        'system:backup': '数据备份',
        'system:log': '系统日志',
        'system:monitor': '系统监控',
        'report:view': '查看报表',
        'report:export': '导出报表',
        'report:create': '创建报表',
        'report:schedule': '定时报表',
        'notification:send': '发送通知',
        'notification:template': '通知模板',
        'notification:schedule': '定时通知'
      }
      return permissionMap[permission] || permission
    }

    return {
      formRef,
      submitting,
      form,
      rules,
      handleTemplateChange,
      getTicketPermissions,
      getUserPermissions,
      getSystemPermissions,
      getReportPermissions,
      handleSubmit,
      handleCancel,
      translateRole,
      translatePermission
    }
  }
}
</script>

<style scoped>
.permission-management {
  max-height: 80vh;
  overflow-y: auto;
}

.user-info-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.user-role {
  font-size: 14px;
  color: #606266;
}

.permission-section {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.permission-group {
  margin-bottom: 16px;
}

.permission-group:last-child {
  margin-bottom: 0;
}

.permission-group h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.permission-group .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.permission-group .el-checkbox {
  margin-right: 0;
}

.form-tip {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
}

.preview-card {
  margin-top: 20px;
}

.preview-card h4 {
  margin: 0;
  color: #303133;
}

.permission-preview {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-section h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
  }
  
  .permission-group .el-checkbox-group {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .permission-tags {
    justify-content: center;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
